package validation;

import org.zkoss.zk.ui.event.*;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.*;
import org.zkoss.image.*;
import java.io.*;
import java.util.*;
import java.io.IOException; 
import org.zkoss.sound.AAudio;

public class VCodeProcessor implements EventListener { 
	private VCodeGenerator vg=new VCodeGenerator();
	private static final int AUDIO_LEN=8;

	public void onEvent(Event e)
	throws IOException{
		Window namespaceHolder=((Window)e.getTarget().getFellow("VG_PANE"));
		if(namespaceHolder == null) return;
		String str=new String(namespaceHolder.getAttribute("EVENT_TYPE").toString());
		
		if(str.equals("REQUEST_NEW_CODE")){
			org.zkoss.zul.Image img=
				((org.zkoss.zul.Image)e.getTarget().getFellow("VG_IMG"));
			
			StringBuffer code=new StringBuffer();
			InputStream	in=vg.getImg(code);
			img.setAttribute("code", code);
			img.setContent(new AImage("code",in));
			img.setAttribute("found", "true");
		
		}else if(str.equals("REQUEST_NEW_VOICE")){
			org.zkoss.zul.Image img=
				((org.zkoss.zul.Image)e.getTarget().getFellow("VG_IMG"));
			Audio player=((Audio)e.getTarget().getFellow("VG_VOICE_PLAYER"));
			
			StringBuffer code=new StringBuffer();
			vg.getRandCode(AUDIO_LEN, code);
			img.setAttribute("code", code);
			
			ByteArrayOutputStream out=VSoundGenerator.getSound(code.toString());
			if(out == null){
				img.setAttribute("found", "false");
				return;
			}
			player.setContent(new AAudio("SoundCode",out.toByteArray()));
			img.setAttribute("found", "true");
			img.setSrc(img.getAttribute("src").toString());
			
		}else{
			org.zkoss.zul.Image img=((org.zkoss.zul.Image)e.getTarget().getFellow("VG_IMG"));
			img.setAttribute("found", "false");
		}
	}
	
} 
